package com.dykj.fireFighting.web.statistic;

import com.dykj.fireFighting.api.base.dev.service.IDevHisWaterZcService;
import com.dykj.fireFighting.api.base.devHisResult.entity.DevHisResult;
import com.dykj.fireFighting.api.base.devHisResult.service.IDevHisResultService;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.maintenance.service.IUrgentMaintenanceService;
import com.dykj.fireFighting.api.base.maintenance.vo.MaintenanceEvaluationVo;
import com.dykj.fireFighting.api.base.statistic.SocialSocreVo;
import com.dykj.fireFighting.api.socialUnit.devHis.service.IDevHisService;
import com.dykj.fireFighting.api.socialUnit.dutymanger.service.IDutyRecordService;
import com.dykj.fireFighting.api.socialUnit.xfxg.service.IPatrolReportService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 评分
 */
@Slf4j
@Api(value = "社会单位评分接口", tags = {"社会单位评分接口"})
@RestController
@RequestMapping("/score")
public class ScoreController {
    @DubboReference
    private IDevHisService devHisService;
    @DubboReference
    private com.dykj.fireFighting.api.base.dev.service.IDevHisService iDevHisService;
    @DubboReference
    private IUrgentMaintenanceService urgentMaintenanceService;
    @DubboReference
    private IPatrolReportService iPatrolReportService;
    @DubboReference
    private IDevHisWaterZcService devHisWaterZcService;
    @DubboReference
    private IDutyRecordService iDutyRecordService;
    @DubboReference
    private IEnterpriseService iEnterpriseService;
    @DubboReference
    private IDevHisResultService devHisResultService;

    /**
     * 根据时间区间获取社会单位的评分
     *
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/data")
    public CommonResult getData(String start, String end) throws Exception {
        List<Enterprise> list = new ArrayList<>();

        if (StringUtils.isBlank(start)) {
            start = DateUtil.getBeforeHalfYearDateStr(new Date());
            end =  DateUtil.getNowDateStr();
        }

        //获取用户类型，监控中心查下辖的单位，社会单位查自己，管理员查全部社会单位
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        if (loginUserVo.getUserType() == 0) {
            //获取所有
            list = iEnterpriseService.getAllSocialUnit();
        } else {
            if (loginUserVo.getEnterpriseType() == 0) {
                Enterprise enterprise = new Enterprise();
                enterprise.setId((loginUserVo.getEnterpriseId()));
                enterprise.setEnterpriseName(loginUserVo.getEnterpriseName());
                list.add(enterprise);
            } else if (loginUserVo.getEnterpriseType() == 2) {
                list = iEnterpriseService.queryUnitSelect(loginUserVo.getEnterpriseId().toString());
            }

        }

        List<SocialSocreVo> socreVoList = new ArrayList<>();

        for (Enterprise enterprise : list) {
            DevHisResult devHisResult = devHisResultService.getUnitNum(enterprise.getId().toString(), start, end);

            SocialSocreVo socialSocreVo = new SocialSocreVo();
            socialSocreVo.setId(enterprise.getId());
            socialSocreVo.setName(enterprise.getEnterpriseName());
            /**火警率得分 */
            int fireRateScore = devHisService.getFireRateScore(start, end, enterprise.getId().toString());
            socialSocreVo.setFireRateScore(fireRateScore);

            /**火警有效复核率 */
            int fireYXFHScore = 0;
            HashMap<String, Object> params = new HashMap<>(16);
            params.put("beginDate", start);
            params.put("endDate", end);
            params.put("unitId", enterprise.getId().toString());
            //已复核总数
            //int total = iDevHisService.getAlreadyReviewCount(params);
            int total = devHisResult.getReviewAll();
            //有效复核数
            //int effect = iDevHisService.getEffectCount(params);
            int effect = devHisResult.getReview();
            if (total == 0) {
                fireYXFHScore = 20;
            } else {
                double fhRate = (double) effect / total;
                if (fhRate == 1) {
                    fireYXFHScore = 20;
                }
                if (fhRate > 0.8 && fhRate < 1) {
                    fireYXFHScore = 15;
                }
                if (fhRate <= 0.8) {
                    fireYXFHScore = 0;
                }
            }
            socialSocreVo.setFireYXFHScore(fireYXFHScore);
            /**预警有效复核率20分*/
            int warnFHRate = 0;
            int watertotal = devHisResult.getManagementAll();
            //int watertotal = iDevHisService.getAlreadyReviewCount(params);
            if (0 == watertotal) {
                warnFHRate = 20;
            } else {
                //有效复核数
                int effectWater = devHisResult.getManagement();
                //int effectWater = devHisWaterZcService.getEffectCount(params);
                double num = (double) effectWater / (double) watertotal;
                if (num == 1) {
                    warnFHRate = 20;
                }
                if (num > 0.8 && num < 1) {
                    warnFHRate = 15;
                }
                if (num <= 0.8) {
                    warnFHRate = 0;
                }
            }
            socialSocreVo.setWarnFHRate(warnFHRate);
            /**故障率（10分）*/
            int fireGZRateScore = devHisService.getFireGZRateScore(start, end, enterprise.getId().toString());
            socialSocreVo.setFireGZRateScore(fireGZRateScore);
            /**消防安全巡查（10分）扣分制*/
            int safeSocre = iPatrolReportService.getSocre(start, end, enterprise.getId().toString());
            socialSocreVo.setSafeSocre(safeSocre);

            /**值班记录10分） 扣分制**/

            int zbScore = iDutyRecordService.getSocScore(start, end, enterprise.getId().toString());
            socialSocreVo.setZbScore(zbScore);

            /***隐患有效整改率*/
            int urgmentSocre = urgentMaintenanceService.getSociologyUrgentSocre(start, end, enterprise.getId().toString());
            socialSocreVo.setUrgmentSocre(urgmentSocre);
            int totalSocal = fireRateScore + fireYXFHScore + warnFHRate + fireGZRateScore + safeSocre + zbScore + urgmentSocre;
            socialSocreVo.setTotalScore(totalSocal);
            socreVoList.add(socialSocreVo);

        }
        //list排序
        List<SocialSocreVo> returnSocreList = socreVoList.stream().sorted(Comparator.comparing(SocialSocreVo::getTotalScore).reversed()).collect(Collectors.toList());
        return CommonResult.success(returnSocreList);
    }

    /**
     * 维保机构当月所有被服务的社会单位评价得分的平均值
     *
     * @return
     */
    @AutoLog(value = "维保机构当月评价得分的平均值")
    @ApiOperation(value = "维保机构当月评价得分的平均值", notes = "维保机构当月评价得分的平均值")
    @GetMapping("/queryMaintenanceEvaluationAvgList")
    public CommonResult<List<MaintenanceEvaluationVo>> queryMaintenanceEvaluationAvgList() {
        String unitId = ShiroUtil.getUser().getEnterpriseId().toString();
        List<MaintenanceEvaluationVo> maintenanceEvaluationVoList = urgentMaintenanceService.queryMaintenanceEvaluationAvgListByUnit(unitId);
        return CommonResult.success(maintenanceEvaluationVoList);
    }

}
